package com.ytjj.qmyx.supplychain.service;

import com.ytjj.qmyx.supplychain.mapper.ReturnDutyMapper;
import com.ytjj.qmyx.supplychain.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.ReturnDuty;
import com.ytjj.qmyx.supplychain.mapper.entity.YxReturnGoods;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

@Service
public class ReturnDutyService {

    @Resource
    private ReturnDutyMapper returnDutyMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateReturnDuty(ReturnDuty request) {
        Example example = new Example(ReturnDuty.class);
        example.createCriteria().andEqualTo("serviceNo",request.getServiceNo());
        example.setOrderByClause("id desc limit 1");
        int i = returnDutyMapper.selectCountByExample(example);
        request.setId(null);
        if (i > 0){
            ReturnDuty returnDuty = returnDutyMapper.selectOneByExample(example);
            Integer id = returnDuty.getId();
            BeanUtils.copyProperties(request,returnDuty);
            returnDuty.setId(id);
            returnDutyMapper.updateByPrimaryKeySelective(returnDuty);
        }else {
            returnDutyMapper.insertSelective(request);
        }
        if(null != request.getReturnDutyFee()){
            YxReturnGoods yxReturnGoods = new YxReturnGoods();
            yxReturnGoods.setServiceNo(request.getServiceNo());
            yxReturnGoods.setAmount(request.getReturnDutyFee());
            returnGoodsMapper.updateByServiceNo(yxReturnGoods);
        }
    }
}
